import {
	defineStore
} from 'pinia';
import LoginApi from '@/ya/api/login.js';

// 默认用户信息
const defaultUserInfo = {
	eid: '', //用户编号
	xb: '',
	idCard: '',
	ename: '',
	ephone: '',
	zkzh: '',
};

const user = defineStore('user', {
	state: () => ({
		userInfo: defaultUserInfo, // 用户信息
		storeList: [],
		isLogin: !!uni.getStorageSync('token'), // 登录状态
		loginType: 1,
		userType: null,
		lastUpdateTime: 0, // 上次更新时间
		tokenExpires: 0, // 新增token过期时间戳
		examInfoList: [],
		userLocation: {}
	}),
	getters: {
		// 新增token有效期检查
		isTokenValid: (state) => {
			return Date.now() < state.tokenExpires
		}
	},
	actions: {
		// 登录
		async login(userInfo) {
			console.log(userInfo);
			const res = await LoginApi.loginPost(userInfo);
			const removeDuplicatesByProps = (arr) => {
				const map = new Map();
				return arr.filter(item => {
					// 复制对象并删除 eid 属性
					const {
						eid,
						...rest
					} = {
						...item
					};
					const key = JSON.stringify(rest);
					if (!map.has(key)) {
						map.set(key, item);
						return true;
					}
					return false;
				});
			};
			console.log('loginPost:', res);
			if (res && res.code == 200) {
				let {
					adminInfo,
					patrolInfo,
					examineeInfo,
					loginType,
					tokenInfo
				} = res.data;
				this.loginType = parseInt(loginType);
				switch (loginType) {
					case 1:
						// 数据去重
						examineeInfo = removeDuplicatesByProps(examineeInfo);
						this.setUserInfo(examineeInfo[0]);
						this.examInfoList = Object.values(examineeInfo);
						break;
					case 2:
						this.setUserInfo(patrolInfo[0]);
						this.examInfoList = Object.values(patrolInfo);
						break;
					case 3:
						this.userInfo = adminInfo;
						this.userType = adminInfo.userType;
						break;
					default:
						this.resetUserData();
						break;
				}
				// this.setToken(tokenInfo);
				return Promise.resolve(true);
			} else {
				uni.showToast({
					title: res.message,
					icon: 'none',
				})
				return Promise.resolve(false);
			}
		},
		// 获取用户信息
		async getInfo() {
			const {
				code,
				data
			} = await LoginApi.getUserInfo();
			if (code !== 0) {
				return;
			}
			this.userInfo = data;
			return Promise.resolve(data);
		},
		// 获取用户位置
		async getLocation() {
			var _this = this;
			try {
				// WGS84（GPS原始）: 39.908722, 116.397497
				// GCJ02（腾讯/高德）: 39.908722, 116.403873
				// BD09（百度）: 39.915071, 116.403927
				// 判断是否是 UniApp 环境
				console.log('user getLocation')
				const settingRes = await uni.getSetting();
				console.log('settingRes', settingRes)
				if (!settingRes.authSetting['scope.userLocation']) {
					const authRes = await uni.getSetting({
						scope: 'scope.userLocation'
					});

					if (!authRes.authSetting['scope.userLocation']) {
						uni.showModal({
							title: '位置权限申请',
							content: '需要获取您的位置信息用于停车导航',
							confirmText: '去设置',
							success(res) {
								if (res.confirm) {
									uni.openSetting()
								}
							}
						})
					}
				}
				return new Promise((resolve, reject) => {
					wx.showLoading({
						title: '获取中...',
						mask: true
					});
					uni.getLocation({
						type: 'gcj02',
						altitude: true,
						success(locationRes) {
							console.log('user-get-locationRes:',
								locationRes)
							_this.updateLocation(locationRes);
							resolve(locationRes);
						},
						fail(err) {
							reject(err);
							uni.showToast({
								title: '获取位置失败',
								icon: 'none'
							})
						}
					});
					wx.hideLoading();
				});
			} catch (err) {
				console.error('获取位置失败:', err);
			}
		},
		// 设置 token
		setToken(tokenInfo, refreshToken = '') {
			console.log('setToken', tokenInfo);
			if (!tokenInfo) {
				this.isLogin = false;
				uni.removeStorageSync('token');
				uni.removeStorageSync('refresh-token');
			} else {
				const {
					expiresIn,
					token,
					type
				} = tokenInfo
				this.isLogin = true;
				// 计算过期时间戳（当前时间 + 有效期秒数 * 1000）
				this.tokenExpires = Date.now() + expiresIn * 1000;
				uni.setStorageSync('token', type + ' ' + token);
				uni.setStorageSync('refresh-token', refreshToken);
				// this.loginAfter();
			}
			return this.isLogin;
		},
		// 设置用户信息
		setUserInfo(data) {
			console.log("设置用户信息：", data)
			// 先清空用户数据
			this.userInfo = {};
			const userInfoKeys = {
				1: ['eid', 'xb', 'ename', 'zkzh', 'ephone', 'idCard'],
				2: ['pid', 'xb', 'pname', 'pzjh', 'pphone', 'idCard'],
				3: ['eid', 'xb', 'ename', 'zkzh', 'ephone', 'idCard']
			};
			userInfoKeys[this.loginType].forEach(item => {
				this.userInfo[item] = data[item]
			})
			console.log("用户信息：", this.userInfo)
			return this.userInfo;
		},
		// 重置用户默认数据
		resetUserData() {
			// 清空 token
			this.setToken({});
			uni.removeStorageSync("userInfo");
			// 清空用户相关的缓存
			this.userInfo = defaultUserInfo;
		},
		updateLocation(res) {
			this.userLocation = res;
		},
		// 登录后，加载各种信息
		async loginAfter() {
			// 加载数据字典
			// await appConfig().getDictData();
		},

		// 登出系统
		async logout() {
			this.resetUserData();
			return !this.isLogin;
		},
		// 新增token刷新方法
		async refreshToken() {
			try {
				const refreshToken = uni.getStorageSync('refresh-token');
				const res = await LoginApi.refreshToken({
					refresh_token: refreshToken
				});

				if (res.code === 200) {
					this.setToken(res.data);
					return true;
				}
			} catch (e) {
				console.error('刷新token失败:', e);
				this.logout();
				uni.showToast({
					title: '登录已过期，请重新登录',
					icon: 'none'
				});
				return false;
			}
		}
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'user-store',
			paths: ['tokenExpires'] // 新增持久化字段
		}]
	},
});

export default user